package cn.touna.jss.modules.third.pcac;

import cn.touna.risk.api.enums.SystemErrorCodeEnum;
import cn.touna.jss.common.factory.ResponseFactory;
import cn.touna.jss.common.properties.disconf.PcacProperties;
import cn.touna.jss.common.util.ValidUtil;
import cn.touna.jss.modules.adapter.ApiMapping;
import cn.touna.jss.modules.third.pcac.entity.PcacRequestEntity;
import cn.touna.risk.api.domain.Response;
import com.alibaba.fastjson.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * Created by Steve.Tao on 2017/11/24.
 */
@Service
public class PcacService {

    @Autowired
    private PcacProperties config;

    private final static Logger logger = LogManager.getLogger();

    @ApiMapping("pcac.queryRiskInfo")
    public Response queryRiskInfo(PcacRequestEntity request) {
        Response response = ValidUtil.valid(request);
        if(response != null){
            return response;
        }
        String lastResult = null;
        int reqCnt = 0;
        try {
            String tid = getTid(request.getName(), request.getIdCard(), "03", 3);
            JSONObject requestData = new JSONObject();
            requestData.put("memberNo", config.getMemberNo());
            requestData.put("version", "1.0");

            JSONObject data = new JSONObject();
            data.put("action", "result");
            data.put("tid", tid);

            requestData.put("data", data);
            if (config.getCallCount() < 1)
                config.setCallCount(1);
            String reqStr = requestData.toJSONString();
            String res = "";
            for (int i = 0; i < config.getCallCount(); i++) {
                lastResult = null;
                try {
                    Thread.sleep(config.getInterval());
                } catch (Exception e) {
                    logger.error("【支付结算协会】接口间调用等待间隔被打断", e);
                }
                res = post(reqStr);
                JSONObject resObj = JSONObject.parseObject(res);
                if ("0".equals(resObj.getString("status"))) {
                    break;
                }
                reqCnt ++;
                lastResult = res;
            }
            return ResponseFactory.success(res);
        } catch (Exception e) {
            logger.error("【支付结算协会】调用失败", e);
            if(reqCnt > 0){
                return ResponseFactory.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_ERROR, e.getMessage(),lastResult);
            }
            return ResponseFactory.fail(SystemErrorCodeEnum.JSS_CALL_EXTSYSTEM_ERROR,e.getMessage());
        }
    }

    @Resource(name = "httpRestTemplate")
    private RestTemplate restTemplate;

    private String getTid(String name, String idCard, String idType, int period) throws Exception {
        JSONObject requestData = new JSONObject();
        requestData.put("memberNo", config.getMemberNo());
        requestData.put("version", "1.0");

        JSONObject data = new JSONObject();
        data.put("action", "query");
        data.put("name", name);
        data.put("idNo", idCard);
        data.put("idType", idType);
        data.put("period", period);
        requestData.put("data", data);

        String res = post(requestData.toJSONString());
        JSONObject resObj = JSONObject.parseObject(res);
        if ("0".equals(resObj.getString("status"))) {
            String tid = resObj.getJSONObject("data").getString("tid");
            return tid;
        } else {
            String message = resObj.getString("message");
            throw new Exception(message);
        }
    }

    private String post(String requestData) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
        map.add("requestData", requestData);

        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
        String res = restTemplate.postForObject(config.getQueryRiskInfoUrl(), request, String.class);
        return res;
    }
}
